package com.jdy.haoduoai.fragment;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.drawable.AnimationDrawable;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.content.ContextCompat;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.Button;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.jdy.haoduoai.Constant;
import com.jdy.haoduoai.LeXiaoXiaoBanApp;
import com.jdy.haoduoai.activity.AbilityTestExplainActivity;
import com.jdy.haoduoai.activity.BaseActivity;
import com.jdy.haoduoai.activity.DevicePropertyActivity;
import com.jdy.haoduoai.activity.HistoryTestResultActivity;
import com.jdy.haoduoai.activity.MyPainPointSelectActivity;
import com.jdy.haoduoai.activity.PersonalInformationActivity2;
import com.jdy.haoduoai.adapter.BabyHabitAdapter;
import com.jdy.haoduoai.adapter.CategoryGridViewAdapter;
import com.jdy.haoduoai.adapter.CategoryGridViewAdapter.OnGridItemClickListener;
import com.jdy.haoduoai.adapter.HabitPlanAdapter;
import com.jdy.haoduoai.adapter.HabitPlanAdapter.OnSetAlarmListener;
import com.jdy.haoduoai.adapter.MyTaskAdapter;
import com.jdy.haoduoai.adapter.MyTaskAdapter.OnCheckListener;
import com.jdy.haoduoai.adapter.OnPreviewClickListener;
import com.jdy.haoduoai.enums.MediaType;
import com.jdy.haoduoai.enums.PlayState;
import com.jdy.haoduoai.intface.IAsyncTask;
import com.jdy.haoduoai.model.CurrentGrowth_info;
import com.jdy.haoduoai.model.HabitMedia;
import com.jdy.haoduoai.model.HabitPlan;
import com.jdy.haoduoai.model.ImUserSig;
import com.jdy.haoduoai.model.LeAudioActionItem;
import com.jdy.haoduoai.model.LeAudioActionPlan;
import com.jdy.haoduoai.model.LeMachine;
import com.jdy.haoduoai.model.LeResourceItem;
import com.jdy.haoduoai.model.LeUser;
import com.jdy.haoduoai.model.LeWatchingPlan;
import com.jdy.haoduoai.model.MainPageResult;
import com.jdy.haoduoai.model.PainPointItem;
import com.jdy.haoduoai.parse.JsonSerializer;
import com.jdy.haoduoai.rx.util.async.Async;
import com.jdy.haoduoai.socket.DeviceStateListener;
import com.jdy.haoduoai.socket.SocketThreadManager;
import com.jdy.haoduoai.util.CommonUtil;
import com.jdy.haoduoai.util.CustomAsyncTask;
import com.jdy.haoduoai.util.DateUtils;
import com.jdy.haoduoai.util.HttpUtils;
import com.jdy.haoduoai.util.ImageLoader;
import com.jdy.haoduoai.util.ImageUtils;
import com.jdy.haoduoai.util.LeConfig;
import com.jdy.haoduoai.util.LePreference;
import com.jdy.haoduoai.util.OnDataReceivedListener;
import com.jdy.haoduoai.util.PathUtil;
import com.jdy.haoduoai.util.ResponseResult;
import com.jdy.haoduoai.util.Tools;
import com.jdy.haoduoai.view.RefreshableView;
import com.jdy.haoduoai.view.RefreshableView.RefreshListener;
import com.jdy.haoduoai.view.RoundImageView;
import com.jdy.haoduoai.view.ScrollViewWithListView;
import com.jdy.haoduoai.view.calendar.adpter.WeekCalendarAdpter.OnDateSelectListener;
import com.jdy.haoduoai.view.calendar.fragment.MyCalendarFragment;
import com.jdy.haoduoai.view.scrollview.ObservableScrollView;
import com.jdy.haoduoai.view.scrollview.OnScrollChangedCallback;
import com.jdy.haoduoai.view.swipemenu.SwipeMenu;
import com.jdy.haoduoai.view.swipemenu.SwipeMenuCreator;
import com.jdy.haoduoai.view.swipemenu.SwipeMenuItem;
import com.jdy.haoduoai.view.swipemenu.SwipeMenuListView;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.squareup.picasso.Callback;
import com.squareup.picasso.Picasso;
import com.umeng.analytics.MobclickAgent;
import com.ycsj.goldmedalnewconcept.R;

import org.droidparts.annotation.inject.InjectView;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;

import rx.functions.Action0;
import rx.functions.Action1;
import rx.functions.Func0;
import rx.functions.Func1;

import static android.view.View.GONE;

//@SuppressLint({ "InflateParams", "HandlerLeak" })
public class TabIndexFragment extends BaseFragment implements
        OnGridItemClickListener, OnScrollListener, OnClickListener,
    OnCompletionListener, RefreshListener, OnCheckListener, OnSetAlarmListener,
        OnDateSelectListener, OnDataReceivedListener,
        DeviceStateListener, OnScrollChangedCallback, BabyHabitAdapter.OnConfirmClassListener, BabyHabitAdapter.OnSetAlarmListener2 {

  private static final String TAG = TabIndexFragment.class.getSimpleName();
  @InjectView(id = R.id.custom_channel)
  private LinearLayout custom_channel;
  @InjectView(id = R.id.h_scrollview)
  private HorizontalScrollView h_scrollview;
  @InjectView(id = R.id.btn_customclass, click = true)
  private Button btn_customclass;
  @InjectView(id = R.id.tv_score)
  private TextView tv_score;
  @InjectView(id = R.id.headicon, click = true)
  private RoundImageView headicon;
  @InjectView(id = R.id.task_views, click = true)
  private ScrollViewWithListView task_views;
  @InjectView(id = R.id.teacherclass_views, click = true)
  private ScrollViewWithListView teacherclass_views;
  @InjectView(id = R.id.list_habitplan, click = true)
  private SwipeMenuListView listview_habitplan;
  @InjectView(id = R.id.refreshableview)
  private RefreshableView mRefreshableView;
  @InjectView(id = R.id.view_score, click = true)
  private View view_score;
  @InjectView(id = R.id.btn_beginclass, click = true)
  private Button btn_beginclass;
  @InjectView(id = R.id.tv_name)
  private TextView tv_name;
  @InjectView(id = R.id.tv_age)
  private TextView tv_age;
  @InjectView(id = R.id.view_nameage, click = true)
  private View view_nameage;
  @InjectView(id = R.id.view_growinfo, click = true)
  private View view_growinfo;
  @InjectView(id = R.id.tv_task)
  private TextView tv_task;
  @InjectView(id = R.id.img_defaultempty)
  private ImageView img_defaultempty; // 过期或未来占位图
  @InjectView(id = R.id.view_habit)
  private View view_habit;
  @InjectView(id = R.id.llayout_defaultempty)
  private LinearLayout llayout_defaultempty; // 过期或未来占位图
  @InjectView(id = R.id.layout_task, click = true)
  private LinearLayout layout_task;
  @InjectView(id = R.id.tv_growthtitle)
  private TextView tv_growthtitle;
  @InjectView(id = R.id.view_content)
  private LinearLayout view_content;
  @InjectView(id = R.id.rel_teacher)
  private View rel_teacher;
  private TextView tvDate;
  private TextView tv_habitlabel;
  private TextView tv_recustom;
  @InjectView(id = R.id.scroll_view)
  private ObservableScrollView scroll_view;
  @SuppressWarnings("unused")
  private BaseActivity mBaseActivity;

  private HabitPlanAdapter mHabitPlanAdapter;
  private ArrayList<HabitPlan> arrayListHabitPlan;
  private BroadcastReceiver mReceiver = null;
  private BabyHabitAdapter mTeacherClassApater;
  private ArrayList<HabitPlan> arrayListTeacherClass;
  private boolean loading;
  public DisplayImageOptions options;
  public ArrayList<String> listTaskDays = new ArrayList<String>();
  private Bitmap mScaleCrop;
  private CategoryGridViewAdapter mCategoryListAdapter;
  private PlayState mPlayState = PlayState.None;
  private int mVideoId = -1;
  private ArrayList<ImageView> imgList = new ArrayList<ImageView>();
  private LeUser mLeUser;
  private MyCalendarFragment myCalenderFragment;
  public static int allowEditTime = 0; // >0: 今天之后， =0 ： 今天 ， <0 ：今天之前
  private boolean isWeekView = true;
  private LeMachine mLeBaby;
  private ImageLoader mImageLoader;
  private boolean isPrepared = true;
  protected boolean isVisible;
  private MainPageResult mMainPageResult;
  private CurrentGrowth_info mCurrentGrowth_info;
  private boolean isImLogin;
  private String lastIMContent;
  private ImUserSig mUserSigWrapper;
  private HabitMedia mHabitMusic;
  private boolean isPlayingMusic;
  private int year_c = 0;
  private int month_c = 0;
  private String currentDate = "";
  private MyTaskAdapter mMyTaskAdapter;
  private ArrayList<LeAudioActionItem> listLeActionItem = new ArrayList<LeAudioActionItem>();
  private boolean isPageChanged;
  private String mCustomDate;
  private LeWatchingPlan mLeWatchingPlanWeek;
  private String mCurDay;
  private String selectQueryDate;
  private TextView mLastTv = null;
  private int mSelectedId = -1;
  private String mLastUrl;
  private boolean mIsPreviewing = false;

  // -1：过去 0：当天 1：将来
  private int dateStatus = -2;

  public static ArrayList<Integer> mSelectedPainPointIds = new ArrayList<Integer>();
  public static ArrayList<PainPointItem> mPainPointList;

  @SuppressLint("ValidFragment")
  public TabIndexFragment(BaseActivity ba) {
    mBaseActivity = ba;
  }

  public TabIndexFragment() {
  }

  private void startAnimation(TextView tv) {
    if (tv != null) {
      AnimationDrawable ad = (AnimationDrawable) ContextCompat.getDrawable(getActivity(),R.drawable.preview_anim);
      tv.setCompoundDrawablesWithIntrinsicBounds(null, null, ad, null);
      ad.start();
    }
  }

  private void unBind() {
    if (SocketThreadManager.getInstance() != null) {
      SocketThreadManager.getInstance().removeDeviceStateListener(TabIndexFragment.this);
      SocketThreadManager.getInstance().removeDataReceivedListener(TabIndexFragment.this);
    }
  }

  private void stopAnimation(TextView tv) {
    if (tv != null) {
      Drawable[] drawables = tv.getCompoundDrawables();
      Drawable rightD = drawables[2];
      if (rightD instanceof AnimationDrawable) {
        AnimationDrawable ad = (AnimationDrawable) rightD;
        if (ad != null && ad.isRunning()) {
          ad.stop();
        }
        Drawable d = ContextCompat.getDrawable(getActivity(),R.drawable.preview_record_img);
        tv.setCompoundDrawablesWithIntrinsicBounds(null, null, d, null);
      } else {
        return;
      }
    }
  }

  private void bindService() {
    if (SocketThreadManager.getInstance() != null) {
      SocketThreadManager.getInstance().setDeviceStateListener(
              TabIndexFragment.this);
      SocketThreadManager.getInstance().requestDeviceDetails();

    }
  }

  @SuppressLint("HandlerLeak")
  private Handler handler = new Handler() {
    @Override
    public void handleMessage(Message msg) {
      super.handleMessage(msg);
      // TODO
    }
  };

  private void getPainpointList() {
    new CustomAsyncTask(getActivity(), new IAsyncTask() {
      @SuppressWarnings("unchecked")
      @Override
      public void onRecieveData(Activity activity, ResponseResult result) {
        if (result.isSuccess()) {
          mSelectedPainPointIds.clear();

          ArrayList<PainPointItem> list = (ArrayList<PainPointItem>) JsonSerializer
              .getInstance().deserialize(result.data, ArrayList.class,
                  PainPointItem.class);

          if (mPainPointList == null) {
            mPainPointList = new ArrayList<PainPointItem>();
          } else {
            mPainPointList.clear();
          }

          for (PainPointItem ppi : list) {
            mPainPointList.add(ppi);
            if (ppi.selected) {
              mSelectedPainPointIds.add(ppi.id);
            }
          }
        }
      }

      @Override
      public ResponseResult doInbackground(Activity activity) {
        HashMap<String, Object> param_ = new HashMap<String, Object>();

        LeUser lu = LeXiaoXiaoBanApp.getInstance().getUser();
        if (lu == null) {
          lu = Tools.restoreLeUser();
        }

        param_.put(HttpUtils.TAG_SNO_I, lu.sno);

        return HttpUtils.startRequest(HttpUtils.API_URL
            + HttpUtils.GET_PAINPOINT_LIST_GET, param_,
            HttpUtils.TAG_GET_REQUEST);
      }
    }).execute();
  }

  private void addEmptyView() {
    if (listview_habitplan.getEmptyView() != null) {
      return;
    }

    View emptyView = LayoutInflater.from(getActivity()).inflate(
        R.layout.tabindex_emptyview, null);

    LinearLayout root_view = (LinearLayout) emptyView
        .findViewById(R.id.root_view);
    Button btn_customhabit = (Button) emptyView
        .findViewById(R.id.btn_customhabit);
    btn_customhabit.setOnTouchListener(CommonUtil.VIEW_TOUCH_DARK);
    btn_customhabit.setOnClickListener(new OnClickListener() {
      @Override
      public void onClick(View v) {
        Intent intent = new Intent();
        intent.setClass(getActivity(), MyPainPointSelectActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
        startActivity(intent);

      }
    });

    LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
        LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
    root_view.setOrientation(LinearLayout.VERTICAL);
    root_view.setGravity(Gravity.CENTER);
    emptyView.setLayoutParams(params);

    ((ViewGroup) listview_habitplan.getParent()).addView(emptyView);
    listview_habitplan.setEmptyView(emptyView);
  }

  @SuppressWarnings("deprecation")
  @SuppressLint({ "ClickableViewAccessibility", "SimpleDateFormat" })
  @Override
  public View onCreateView(Bundle savedInstanceState, LayoutInflater inflater,
      ViewGroup container) {

    ((BaseActivity) getActivity()).showloading("");

    View bodyView = LayoutInflater.from(mContext).inflate(
        R.layout.activity_index, container, false);

    tv_habitlabel = (TextView) bodyView.findViewById(R.id.tv_habitlabel);
    scroll_view = (ObservableScrollView) bodyView
        .findViewById(R.id.scroll_view);
    scroll_view.setOnScrollChangedCallback(TabIndexFragment.this);

    Date date = new Date();
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-M-d");
    currentDate = sdf.format(date);
    year_c = Integer.parseInt(currentDate.split("-")[0]);
    month_c = Integer.parseInt(currentDate.split("-")[1]);

    isPrepared = true;

    tvDate = (TextView) bodyView.findViewById(R.id.tv_date);
    tvDate.setText(year_c + "年" + String.format("%02d月", month_c));

    Drawable drawable;
    if (isWeekView) {
      drawable = getResources().getDrawable(R.drawable.blue_arrow_down);
      drawable.setBounds(0, 0, drawable.getMinimumWidth(),
          drawable.getMinimumHeight());
    } else {
      drawable = getResources().getDrawable(R.drawable.blue_arrow_up);
      drawable.setBounds(0, 0, drawable.getMinimumWidth(),
          drawable.getMinimumHeight());
    }

    task_views = (ScrollViewWithListView) bodyView
        .findViewById(R.id.task_views);

    teacherclass_views = (ScrollViewWithListView) bodyView
            .findViewById(R.id.teacherclass_views);
    teacherclass_views.setEnabled(false);

    tv_recustom = (TextView) bodyView.findViewById(R.id.tv_recustom);
    tv_recustom.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG);
    tv_recustom.setOnClickListener(this);

    listview_habitplan = (SwipeMenuListView) bodyView
        .findViewById(R.id.list_habitplan);
    listview_habitplan.setHiderMore(true);

    SwipeMenuCreator creator = new SwipeMenuCreator() {

      @Override
      public void create(SwipeMenu menu, int pos) {
          if (arrayListHabitPlan.get(pos) != null && arrayListHabitPlan.get(pos).is_customized == 2) {
              return;
          }
        SwipeMenuItem deleteItem = new SwipeMenuItem(mContext);
        deleteItem
            .setBackground(new ColorDrawable(Color.rgb(0xF0, 0xF0, 0xF0)));
        deleteItem.setWidth(Tools.getPixelByDip(mContext, 90));
        deleteItem.setIcon(R.drawable.btn_del);
        menu.addMenuItem(deleteItem);
      }
    };

    listview_habitplan.setMenuCreator(creator);
    listview_habitplan
        .setOnMenuItemClickListener(new SwipeMenuListView.OnMenuItemClickListener() {
          @Override
          public boolean onMenuItemClick(final int position, SwipeMenu menu,
              int index) {
            switch (index) {
            case 0:
              new CustomAsyncTask(getActivity(), new IAsyncTask() {
                @Override
                public void onRecieveData(Activity activity,
                    ResponseResult result) {
                  if (result.isSuccess()) {
                    if (arrayListHabitPlan != null
                        && position < arrayListHabitPlan.size()) {
                      arrayListHabitPlan.remove(position);
                      mHabitPlanAdapter.notifyDataSetChanged();
                    }
                  } else {
                    if (Tools.isNotNullStr(result.data)) {
                      Toast.makeText(getActivity(), result.data,
                          Toast.LENGTH_SHORT).show();
                    }
                  }

                }

                @Override
                public ResponseResult doInbackground(Activity activity) {
                  HashMap<String, Object> param_ = new HashMap<String, Object>();
                  LeUser lu = LeXiaoXiaoBanApp.getInstance().getUser();
                  if (lu == null) {
                    lu = Tools.restoreLeUser();
                  }

                  param_.put(HttpUtils.TAG_SNO_I, lu.sno);

                    if (arrayListHabitPlan.get(position).is_customized == 1) {
                        return HttpUtils.startRequest(HttpUtils.API_URL
                                        + "/api/2.0/operation/habit/habits_customized_plan/"
                                        + arrayListHabitPlan.get(position).id, param_,
                                HttpUtils.TAG_DELETE_REQUEST);
                    } else {
                        return HttpUtils.startRequest(HttpUtils.API_URL
                                        + "/api/2.0/operation/habit/habits_plan/"
                                        + arrayListHabitPlan.get(position).id, param_,
                                HttpUtils.TAG_DELETE_REQUEST);
                    }


                }
              }).execute();

              break;
            }
            return false;
          }
        });

    // set SwipeListener
    listview_habitplan
        .setOnSwipeListener(new SwipeMenuListView.OnSwipeListener() {

          @Override
          public void onSwipeStart(int position) {
            // swipe start
          }

          @Override
          public void onSwipeEnd(int position) {
            // swipe end

          }

          @Override
          public void onClickSwipeOpen(int position) {

          }
        });

    mRefreshableView = (RefreshableView) bodyView
        .findViewById(R.id.refreshableview);

    return bodyView;
  }

  private void updateBeginClassBtn() {
    switch (dateStatus) {
    case -1:
      btn_beginclass.setEnabled(true);
      break;
    case 0:
      btn_beginclass.setEnabled(true);
      btn_beginclass.setBackgroundResource(R.drawable.begin_class_normal);
      break;
    case 1:
      btn_beginclass.setBackgroundResource(R.drawable.begin_class_normal);
      btn_beginclass.setEnabled(false);
      break;

    default:
      break;
    }
  }

  private void updateWeekRecomAnim(String dateStr) {
    mLeWatchingPlanWeek = null;

    if (Tools.isNotEmpty(mMainPageResult)
        && Tools.isNotEmpty(mMainPageResult.clause)
        && !mMainPageResult.clause.isEmpty()) {
      for (LeWatchingPlan item : mMainPageResult.clause) {
        if (dateStr.contains(item.date)) {
          mLeWatchingPlanWeek = item;
          break;
        }
      }
    }

    if (Tools.isNotEmpty(mMainPageResult)
        && Tools.isNotEmpty(mMainPageResult.current_growth_info)) {
      tv_age.setText(mMainPageResult.current_growth_info.age);
      LeXiaoXiaoBanApp.getInstance().kidAge = mMainPageResult.current_growth_info.age;
    } else {
      checkBabyAge();
    }

    fillRecomAnimLineLayout();
  }

  private void init() {
    myCalenderFragment = new MyCalendarFragment(new Handler() {
      @Override
      public void handleMessage(Message msg) {
        super.handleMessage(msg);
      }
    }, false);

    myCalenderFragment.setOnDateSelectListener(this);
    ((BaseActivity) mContext).getSupportFragmentManager().beginTransaction()
        .add(R.id.re_cotent, myCalenderFragment).show(myCalenderFragment)
        .commit();

    mLeUser = LeXiaoXiaoBanApp.getInstance().getUser();
    mLeBaby = LeXiaoXiaoBanApp.getInstance().getBaby();
    if (mLeUser == null) {
      mLeUser = Tools.restoreLeUser();
    }
    if (mLeBaby == null) {
      mLeBaby = Tools.restoreLeBaby();
    }

    if (btn_beginclass != null) {
      btn_beginclass.setOnTouchListener(CommonUtil.VIEW_TOUCH_DARK);
    }

    updateBeginClassBtn();

    selectQueryDate = mCurDay;

    mRefreshableView.setRefreshEnabled(true);
    mRefreshableView.setRefreshListener(this, RefreshableView.ID_MAINPAGE);
    mRefreshableView.bringToFront();

    options = new DisplayImageOptions.Builder()
        .showImageOnFail(R.drawable.default_img_listitem).cacheInMemory(true)
        .bitmapConfig(Bitmap.Config.RGB_565).build();
    ImageLoaderConfiguration configuration = new ImageLoaderConfiguration.Builder(
        getActivity()).writeDebugLogs().build();
    com.nostra13.universalimageloader.core.ImageLoader.getInstance().init(
        configuration);

    if (mLeUser != null) {
      if (Tools.isNotNullStr(mLeUser.machine)) {
        tv_name.setText(mLeUser.machine.name);
      }
    } else if (mLeBaby != null) {
      tv_name.setText(mLeBaby.name);
    }
    setUserAvatar();
  }

  @Override
  public void onAttach(Activity activity) {
    super.onAttach(activity);
    dateStatus = 0;
  }

  @SuppressLint("SimpleDateFormat")
  @Override
  public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

    loading = true;
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    mCurDay = sdf.format(Calendar.getInstance().getTime());

    bindService();
    init();

    mReceiver = new BroadcastReceiver() {
      @Override
      public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        if ("updatebabyheadimage".equals(action)) {
          SharedPreferences prefs = mContext.getSharedPreferences(
              Constant.USER_INFO, Context.MODE_PRIVATE);

          String parentImagePath = prefs.getString(Constant.BABY_AVATAR, "");
          if (Tools.isNotEmpty(parentImagePath)) {
            Uri parentUri = Uri.parse(parentImagePath);

            Bitmap originalBitmap = ImageUtils.getBitmapFromUri(mContext,
                parentUri);
            if (originalBitmap != null) {
              mScaleCrop = ImageUtils.scaleCropToFit(originalBitmap, 300, 300,
                  true);
            }

            headicon.setImageURI(null);
            if (mScaleCrop != null)
              headicon.setImageBitmap(mScaleCrop);
          } else if (Tools.isEmpty(parentImagePath) && mLeBaby != null) {
            getHeadImage(mLeBaby.avatar);
          }
        } else if ("bindNewDeviceSuccess".equals(action)) {

        } else if ("updatepersonalinfo".equals(action)
            && Tools.isNotEmpty(selectQueryDate)) {
          loadDataByMonth(selectQueryDate);
        }
      }
    };

    IntentFilter filter = new IntentFilter();
    filter.addAction("updatepersonalinfo");
    filter.addAction("updatebabyheadimage");
    filter.addAction("bindNewDeviceSuccess");
    mContext.registerReceiver(mReceiver, filter);

    checkUserImSig();
  }

  private void checkUserImSig() {
    String userSig = LePreference.getInstance().getString("usersig");
    if (Tools.isNotEmpty(userSig)) {
      mUserSigWrapper = JsonSerializer.getInstance().deserialize(userSig,
          ImUserSig.class);
    }

    LeMachine lb = LeXiaoXiaoBanApp.getInstance().getBaby();
    SocketThreadManager.getInstance().setDataReceivedListener(TabIndexFragment.this);

    if (handler == null) {
      handler = new Handler();
    }

//    JSONObject jsonObject = new JSONObject();
//    try {
//      jsonObject.put("code", 202);
//      jsonObject.put("act", "connect");
//      jsonObject.put("data", mLeUser.id);
//      SocketThreadManager.getInstance().send(jsonObject.toString());
//      lastIMContent = jsonObject.toString();
//    } catch (JSONException e) {
//      e.printStackTrace();
//    }
  }

  private void getHeadImage(String remoteHeadImageFilePath) {
    if (Tools.isNullStr(remoteHeadImageFilePath)) {
      return;
    }

    SharedPreferences prefs = mContext.getSharedPreferences(Constant.USER_INFO,
        Context.MODE_PRIVATE);

    String babyImagePath = prefs.getString(Constant.BABY_AVATAR, "");
    if (Tools.isNullStr(babyImagePath)) {
      new AsyncTask<String, Void, Bitmap>() {
        @Override
        protected void onPostExecute(Bitmap result) {
          if (result != null) {
            String path = PathUtil.getBabyAvatarPath(mContext
                .getApplicationContext());
            FileOutputStream out = null;
            File babyAvatarFile = new File(path);
            try {
              out = new FileOutputStream(babyAvatarFile);
              result.compress(Bitmap.CompressFormat.PNG, 100, out); // bmp is
                                                                    // your
                                                                    // Bitmap
                                                                    // instance
              // PNG is a lossless format, the compression factor (100) is
              // ignored
              SharedPreferences prefs = mContext.getSharedPreferences(
                  Constant.USER_INFO, Context.MODE_PRIVATE);
              Uri babyAvatarUri = Uri.fromFile(babyAvatarFile);
              prefs.edit()
                  .putString(Constant.BABY_AVATAR, babyAvatarUri.toString())
                  .apply();
            } catch (Exception e) {
              e.printStackTrace();
            } finally {
              try {
                if (out != null) {
                  out.close();
                }
              } catch (IOException e) {
                e.printStackTrace();
              }
            }
          }
        }

        @Override
        protected Bitmap doInBackground(String... urls) {
          String urldisplay = urls[0];
          Bitmap resultImage = null;
          URL url;
          try {
            url = new URL(urldisplay);
            HttpURLConnection urlConnection = (HttpURLConnection) url
                .openConnection();
            urlConnection.setRequestMethod("GET");
            // urlConnection.setDoOutput(true);
            urlConnection.connect();
            InputStream in = urlConnection.getInputStream();
            // InputStream in = new java.net.URL(urldisplay).openStream();
            resultImage = BitmapFactory.decodeStream(in);

          } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
          } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
          }
          return resultImage;
        }
      }.execute(remoteHeadImageFilePath);
    }
  }

  private void setUserAvatar() {
    SharedPreferences prefs = mContext.getSharedPreferences(Constant.USER_INFO,
        Context.MODE_PRIVATE);
    String parentImagePath = prefs.getString(Constant.BABY_AVATAR, "");
    if (Tools.isNotEmpty(parentImagePath)) {
      Uri parentUri = Uri.parse(parentImagePath);

      if (mScaleCrop == null) {
        Bitmap originalBitmap = ImageUtils
            .getBitmapFromUri(mContext, parentUri);
        if (originalBitmap != null) {
          mScaleCrop = ImageUtils
              .scaleCropToFit(originalBitmap, 300, 300, true);
        }
      }

      headicon.setImageURI(null);
      if (mScaleCrop != null)
        headicon.setImageBitmap(mScaleCrop);

    } else if (Tools.isEmpty(parentImagePath) && mLeBaby != null) {
      getHeadImage(mLeBaby.avatar);
    }
  }

  private boolean isLoading, firstLoad = true;

  @SuppressLint("SimpleDateFormat")
  private void loadHabitsPlan(final String dayStr) {
    if (Tools.isNotEmpty(dayStr)) {
      selectQueryDate = dayStr;
      SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
      String strToday = sdf.format(Calendar.getInstance().getTime());

      TabIndexFragment.allowEditTime = dayStr.compareTo(strToday);
    }

    if (isLoading || Tools.isEmpty(dayStr)) {
      return;
    }

    isLoading = true;

    Async.start(new Func0<ResponseResult>() {
      @Override
      public ResponseResult call() {
        LeUser lu = LeXiaoXiaoBanApp.getInstance().getUser();
        if (lu == null) {
          lu = Tools.restoreLeUser();
        }

        HashMap<String, Object> param_ = new HashMap<String, Object>();
        param_.put(HttpUtils.TAG_SNO_I, lu.sno);
        param_.put("date", dayStr);

        return HttpUtils.startRequest(HttpUtils.API_URL
            + "/api/2.0/operation/habit/habits_plan", param_,
            HttpUtils.TAG_GET_REQUEST);
      }
    }).filter(new Func1<ResponseResult, Boolean>() {
      @Override
      public Boolean call(ResponseResult arg0) {
        return arg0 != null && Tools.isNotEmpty(arg0) && arg0.isSuccess();
      }
    }).doOnCompleted(new Action0() {
      @Override
      public void call() {

        if (getActivity() == null) {
          isLoading = false;
          return;
        }

        if (arrayListHabitPlan == null) {
          arrayListHabitPlan = new ArrayList<HabitPlan>();
        }

        if (arrayListTeacherClass == null) {
          arrayListTeacherClass = new ArrayList<HabitPlan>();
        }

        getActivity().runOnUiThread(new Runnable() {
          @Override
          public void run() {

            if (mHabitPlanAdapter == null) {
              mHabitPlanAdapter = new HabitPlanAdapter((BaseActivity) mContext,
                      arrayListHabitPlan, listview_habitplan);
            } else {
              mHabitPlanAdapter.updateListData(arrayListHabitPlan);
            }

            mHabitPlanAdapter.setOnSetAlarmListener(TabIndexFragment.this);
            listview_habitplan.setAdapter(mHabitPlanAdapter);

            if (mTeacherClassApater == null) {
              if (arrayListTeacherClass != null && !arrayListTeacherClass.isEmpty()) {
                mTeacherClassApater = new BabyHabitAdapter(mBaseActivity, arrayListTeacherClass);
                mTeacherClassApater.setConfirmClassListener(TabIndexFragment.this);
                mTeacherClassApater.setOnSetAlarmListener(TabIndexFragment.this);
              } else {
                mTeacherClassApater = new BabyHabitAdapter(mBaseActivity,
                        new ArrayList<HabitPlan>());
                mTeacherClassApater.setConfirmClassListener(TabIndexFragment.this);
                mTeacherClassApater.setOnSetAlarmListener(TabIndexFragment.this);
              }

              teacherclass_views.setAdapter(mTeacherClassApater);
            } else {
              mTeacherClassApater.setData(arrayListTeacherClass);
              mTeacherClassApater.notifyDataSetChanged();
            }

            if (arrayListTeacherClass == null || arrayListTeacherClass.isEmpty()) {
              rel_teacher.setVisibility(GONE);
            } else {
              rel_teacher.setVisibility(View.VISIBLE);
            }

            addEmptyView();

            SimpleDateFormat formatter = new SimpleDateFormat(
                "yyyy-MM-dd HH:mm:ss");
            String strCurentDate = formatter.format(Calendar.getInstance()
                .getTime());
            String date[] = strCurentDate.split(" ");

            if (arrayListHabitPlan != null) {
              for (int i = 0; i < arrayListHabitPlan.size(); i++) {
                HabitPlan item = arrayListHabitPlan.get(i);

                if (item != null) {
                  if (item.time.compareTo(date[1]) >= 0) {
                    if (item.time.compareTo(date[1]) == 0) {
                      item.allowEditTime = false;
                    }
                    if (!isPlayingMusic) {
                      listview_habitplan.setSelection(i);
                    }
                    break;
                  } else {
                    item.allowEditTime = false;
                  }
                }
              }
            }

            listview_habitplan.setFocusable(false);

            if (arrayListHabitPlan == null || arrayListHabitPlan.isEmpty()) {
//              view_habit.setVisibility(GONE);
//              tv_habitlabel.setVisibility(GONE);
//              listview_habitplan.setVisibility(GONE);
            } else {
              view_habit.setVisibility(View.VISIBLE);
              tv_habitlabel.setVisibility(View.VISIBLE);
              listview_habitplan.setVisibility(View.VISIBLE);
            }

            Tools.setListViewHeightBasedOnChildren(listview_habitplan);
            mHabitPlanAdapter.notifyDataSetChanged();
            if (firstLoad) {
              view_growinfo.setFocusable(true);
              view_growinfo.setFocusableInTouchMode(true);
              view_growinfo.requestFocus();
              firstLoad = false;
            }
          }
        });

        isLoading = false;
       // loadCustomHabitsPlan(dayStr);
      }
    }).subscribe(new Action1<ResponseResult>() {
      @SuppressWarnings("unchecked")
      @Override
      public void call(ResponseResult result) {
        if (arrayListTeacherClass == null) {
          arrayListTeacherClass = new ArrayList<HabitPlan>();
        }

        arrayListTeacherClass.clear();

        if (Tools.isNotEmpty(result) && Tools.isNotEmpty(result.data)) {
          arrayListHabitPlan = (ArrayList<HabitPlan>) JsonSerializer
              .getInstance().deserialize(result.data, ArrayList.class,
                  HabitPlan.class);

          for (HabitPlan item : arrayListHabitPlan) {
            if (item.is_customized == 2) {
              arrayListTeacherClass.add(item);
            }
          }

          if (arrayListHabitPlan != null) {
            arrayListHabitPlan.removeAll(arrayListTeacherClass);
          }
        } else {
          arrayListHabitPlan = new ArrayList<HabitPlan>();
          arrayListTeacherClass = new ArrayList<HabitPlan>();
        }
      }
    });
  }

  @SuppressLint("SimpleDateFormat")
  private void checkAnimAndTaskNumber(String dateStr) {
    if (Tools.isNotEmpty(dateStr)) {

      String[] createTime = mLeUser.machine.created_at.split(" ");

      if (dateStr.compareTo(mLeUser.machine.dob) >= 0
          && dateStr.compareTo(createTime[0]) < 0
          || dateStr.compareTo(mLeUser.machine.dob) < 0) {
        tv_task.setVisibility(GONE);
        layout_task.setVisibility(GONE);
       // view_content.setVisibility(GONE);
      //  tv_growthtitle.setVisibility(GONE);

        llayout_defaultempty.setVisibility(View.VISIBLE);
        img_defaultempty.setImageResource(R.drawable.date_passed);
      } else {

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String strToday = sdf.format(Calendar.getInstance().getTime());

        if (dateStr.compareTo(strToday) > 0
            && (mMainPageResult.audio_interaction == null || mMainPageResult.audio_interaction
                .isEmpty())) {
          tv_task.setVisibility(GONE);
          layout_task.setVisibility(GONE);
         // view_content.setVisibility(GONE);
        //  tv_growthtitle.setVisibility(GONE);

          llayout_defaultempty.setVisibility(View.VISIBLE);
          img_defaultempty.setImageResource(R.drawable.date_future);
        } else {
          tv_task.setVisibility(View.VISIBLE);
          layout_task.setVisibility(View.VISIBLE);
         // view_content.setVisibility(View.VISIBLE);
         // tv_growthtitle.setVisibility(View.VISIBLE);
          llayout_defaultempty.setVisibility(GONE);
        }
      }

    } else {
      tv_task.setVisibility(View.VISIBLE);
      layout_task.setVisibility(View.VISIBLE);
     // view_content.setVisibility(View.VISIBLE);
     // tv_growthtitle.setVisibility(View.VISIBLE);
      llayout_defaultempty.setVisibility(GONE);
    }
  }

  private OnCompletionListener mediaPlayerListener = new OnCompletionListener() {
    @Override
    public void onCompletion(MediaPlayer mp) {
      //stopAnimation();
      if (mLastTv!=null) {
        stopAnimation(mLastTv);
      }
    }
  };

  private void previewMp3(String mp3_url) {
    releaseMp3Player();

    boolean excepthappen = false;
    if (mp3Player == null)
      mp3Player = new MediaPlayer();
    try {
      mp3Player.setDataSource(mp3_url);
    } catch (IllegalArgumentException e) {
      excepthappen = true;
      e.printStackTrace();
    } catch (SecurityException e) {
      excepthappen = true;
      e.printStackTrace();
    } catch (IllegalStateException e) {
      excepthappen = true;
      e.printStackTrace();
    } catch (IOException e) {
      excepthappen = true;
      e.printStackTrace();
    }

    if ( !excepthappen ) {
      try {
        mp3Player.prepare();
        mp3Player.start();
        mp3Player.setOnCompletionListener(mediaPlayerListener);
      } catch (IllegalArgumentException e) {
        excepthappen = true;
        e.printStackTrace();
      } catch (SecurityException e) {
        excepthappen = true;
        e.printStackTrace();
      } catch (IllegalStateException e) {
        excepthappen = true;
        e.printStackTrace();
      } catch (IOException e) {
        excepthappen = true;
        e.printStackTrace();
      }
    } else {
     // toastShow("暂时无法试听");
    }
  }

  private MediaPlayer mp3Player;

  private void releaseMp3Player() {
    if (mp3Player != null) {
      mp3Player.stop();
      mp3Player.setOnCompletionListener(null);
      mp3Player.release();
      mp3Player = null;
    }
  }

  @Override
  public void onHiddenChanged(boolean hidden) {
    super.onHiddenChanged(hidden);
  }

  @SuppressLint("SimpleDateFormat")
  private void updateDayTask(String dataStr) {
    if (listLeActionItem == null) {
      listLeActionItem = new ArrayList<>();
    } else {
      listLeActionItem.clear();
    }

    int plan_id = 0;
    if (Tools.isNotEmpty(mMainPageResult)) {
      if (mMainPageResult.audio_interaction != null
          && !mMainPageResult.audio_interaction.isEmpty()) {
        for (LeAudioActionPlan item : mMainPageResult.audio_interaction) {
          if (item != null && item.date.contains(dataStr)) {
            listLeActionItem.addAll(item.actions);
            plan_id = item.interaction_id;
            break;
          }
        }
      }
    }

    mCurrentGrowth_info = mMainPageResult.current_growth_info;

    if (Tools.isNotEmpty(mCurrentGrowth_info)) {
      tv_score.setText(mCurrentGrowth_info.score + "");
    }

    if (listLeActionItem == null) {
      listLeActionItem = new ArrayList<>();
    }

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    String strToday = sdf.format(Calendar.getInstance().getTime());

    boolean clickable;
    if (dataStr.compareTo(strToday) > 0) {
      clickable = false;
    } else if (dataStr.compareTo(strToday) < 0) {
      if (LeXiaoXiaoBanApp.getInstance().getGrowth_period() == mMainPageResult.growth_info.growth_period) {
        clickable = true;
      } else {
        clickable = false;
      }
    } else {
      clickable = true;
    }

    mMyTaskAdapter = new MyTaskAdapter((BaseActivity) mContext,
        listLeActionItem, plan_id, clickable);


    mMyTaskAdapter.setOnPreviewClickListener(new OnPreviewClickListener() {
      @Override
      public void onPreviewClick(TextView tv,int id, String mp3_url) {
        if (id != mSelectedId) {
          stopAnimation(mLastTv);
          startAnimation(tv);
          mIsPreviewing = true;
          previewMp3(mp3_url);
        } else {
          mIsPreviewing = !mIsPreviewing;
          if(mIsPreviewing) {
            startAnimation(tv);
            previewMp3(mp3_url);
          } else {
            stopAnimation(tv);
            releaseMp3Player();
          }
        }
        mLastTv = tv;
        mSelectedId = id;
      }
    });

    mMyTaskAdapter.setOnCheckListener(this);
    task_views.setAdapter(mMyTaskAdapter);

    if (mCurrentGrowth_info != null) {
      if (mCurrentGrowth_info.score == 0) {
        btn_customclass.setVisibility(View.VISIBLE);
        view_score.setVisibility(GONE);
      } else {
        btn_customclass.setVisibility(GONE);
        view_score.setVisibility(View.VISIBLE);
      }
    } else {
      btn_customclass.setVisibility(View.VISIBLE);
      view_score.setVisibility(GONE);
    }

    Tools.setListViewHeightBasedOnChildren(task_views);
    mMyTaskAdapter.notifyDataSetChanged();
  }

  private void loadDataByMonth(final String strDate) {
    // ((BaseActivity) mContext).showloading("");

    new CustomAsyncTask(getActivity(), new IAsyncTask() {
      @SuppressLint("SimpleDateFormat")
      @Override
      public void onRecieveData(Activity activity, ResponseResult result) {
        if (result.isSuccess()) {
          if (Tools.isNotNullStr(result.data)) {
            mMainPageResult = JsonSerializer.getInstance().deserialize(
                result.data, MainPageResult.class);

            if (Tools.isNotEmpty(mMainPageResult)) {

              updateWeekRecomAnim(strDate);
              updateDayTask(strDate);

            }
          }
        }

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String strToday = sdf.format(Calendar.getInstance().getTime());

        if (strDate.compareTo(strToday) < 0) {
          dateStatus = -1;
        } else if (strDate.compareTo(strToday) == 0) {
          dateStatus = 0;
        } else if (strDate.compareTo(strToday) > 0) {
          dateStatus = 1;
        }
        updateBeginClassBtn();

        checkAnimAndTaskNumber(strDate);
        loading = false;
        mRefreshableView.finishRefresh();
        isPageChanged = false;
        ((BaseActivity) mContext).dismissLoading();

        if (firstLoad) {
          view_growinfo.setFocusable(true);
          view_growinfo.setFocusableInTouchMode(true);
          view_growinfo.requestFocus();
          firstLoad = false;
        }

      }

      @Override
      public ResponseResult doInbackground(Activity activity) {
        loading = true;
        if (mLeUser == null) {
          mLeUser = Tools.restoreLeUser();
        }
        HashMap<String, Object> param_ = new HashMap<String, Object>();
        param_.put(HttpUtils.TAG_SNO_I, mLeUser.sno);
        param_.put("date", strDate);

        return HttpUtils.startRequest(
            HttpUtils.API_URL + "/api/2.0/index/date", param_,
            HttpUtils.TAG_GET_REQUEST);
      }
    }).execute();
  }

  private void fillRecomAnimLineLayout() {

    h_scrollview.setOnTouchListener(new View.OnTouchListener() {
      @SuppressLint("ClickableViewAccessibility")
      @Override
      public boolean onTouch(View arg0, MotionEvent arg1) {

        Log.e("chen", "HorizontalScrollView-onTouch");

        // 不能滑动
        return true;
        // 可以滑动
        // return false;
      }
    });

    custom_channel.removeAllViews();

    // View line = new View(getActivity());
    int pCount = 0;
    if (Tools.isNotEmpty(mLeWatchingPlanWeek)
        && Tools.isNotEmpty(mLeWatchingPlanWeek.resources)
        && !mLeWatchingPlanWeek.resources.isEmpty()) {
      pCount = mLeWatchingPlanWeek.resources.size();
    }

    if (pCount > 3) {
      pCount = 3;
    }

    DisplayMetrics dm;
    int screenW;

    dm = new DisplayMetrics();


    if (getActivity()!=null) {
      getActivity().getWindowManager().getDefaultDisplay().getMetrics(dm); // 得到
      // 屏幕的宽度
      screenW = dm.widthPixels;
    } else {
      screenW = LeXiaoXiaoBanApp.getInstance().screenW;
    }


    // screenH = dm.heightPixels;

    imgList.clear();

      Context ctx = LeXiaoXiaoBanApp.getAppContext();


    for (int i = 0; i < pCount; i++) {
      View v = LayoutInflater.from(mContext).inflate(R.layout.class_list_item2,
          custom_channel, false);

      final LeResourceItem item = mLeWatchingPlanWeek.resources.get(i);

      LayoutParams para3333;
      para3333 = v.getLayoutParams();

      para3333.width = (screenW - Tools.getPixelByDip(ctx, 56)) / 3;
      v.setLayoutParams(para3333);

      custom_channel.addView(v);
      final ImageView channelIcon = (ImageView) v.findViewById(R.id.headicon);

      final TextView title = (TextView) v.findViewById(R.id.editor);
      final TextView playtimes = (TextView) v.findViewById(R.id.playtimes);
      final TextView tv_name2 = (TextView) v.findViewById(R.id.tv_name2);
      final TextView tv_label1 = (TextView) v.findViewById(R.id.tv_label1);
      final TextView tv_label2 = (TextView) v.findViewById(R.id.tv_label2);
      final ImageView img_playanim = (ImageView) v
          .findViewById(R.id.img_playanim);
      img_playanim.setTag(item.resource_id);
      imgList.add(img_playanim);

      if (item.tags == null || item.tags.isEmpty()) {
        tv_label1.setVisibility(View.INVISIBLE);
        tv_label2.setVisibility(View.INVISIBLE);
      } else if (item.tags.size() == 1) {
        tv_label1.setText(item.tags.get(0));
        tv_label2.setVisibility(View.INVISIBLE);
      } else if (item.tags.size() > 1) {
        tv_label1.setText(item.tags.get(0));
        tv_label2.setText(item.tags.get(1));
      }

      tv_name2.setText(item.resource_name);
      title.setText(item.album_name);
      playtimes.setText(DateUtils.getTime2(item.length));
      // tv_categorydes.setText(item.type.title);

      if (mImageLoader == null) {
        mImageLoader = new ImageLoader(mContext);
      }

      if (Tools.isNotEmpty(item) && Tools.isNotEmpty(item.album_cover)) {
        Picasso.with(mContext).load(item.album_cover)
            .placeholder(R.drawable.default_img_listitem)
            .error(R.drawable.default_img_listitem)
            .into(channelIcon, new Callback() {
              @Override
              public void onError() {
                mImageLoader.DisplayImage(item.album_cover, channelIcon, false);
              }

              @Override
              public void onSuccess() {
                // TODO Auto-generated method stub
              }
            });
      } else   if (Tools.isNotEmpty(item) && Tools.isNotEmpty(item.album_cover2)) {
        Picasso.with(mContext).load(item.album_cover2)
                .placeholder(R.drawable.default_img_listitem)
                .error(R.drawable.default_img_listitem)
                .into(channelIcon, new Callback() {
                  @Override
                  public void onError() {
                    mImageLoader.DisplayImage(item.album_cover2, channelIcon, false);
                  }

                  @Override
                  public void onSuccess() {
                    // TODO Auto-generated method stub
                  }
                });
      }

      final int videoNum = i;

      img_playanim.setOnTouchListener(CommonUtil.VIEW_TOUCH_DARK);
      img_playanim.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
          if (mMainPageResult != null && mMainPageResult.clause != null
              && !mMainPageResult.clause.isEmpty()) {

            if (mPlayState == PlayState.None || mPlayState == PlayState.Offline
                || mPlayState == PlayState.Stop
                || mPlayState == PlayState.NoResource) {
              playvideo(mMainPageResult.clause.get(0).clause_id, "radio",
                  videoNum, img_playanim);
              img_playanim.setBackgroundResource(R.drawable.anim_pause);

              for (int i = 0; i < imgList.size(); i++) {
                if (i != videoNum) {
                  imgList.get(i).setBackgroundResource(R.drawable.anim_play);
                }
              }

            } else {
              if (mVideoId != -1 && mVideoId == item.resource_id) {
                if (mPlayState == PlayState.Playing) {
                //  if (mImHelper != null && mImHelper.isLogin()) {
                    try {
                      JSONObject jsonObject = new JSONObject();
                      jsonObject.put("code", 202);
                      jsonObject.put("act", "ctlvideo");
                      jsonObject.put("data", "pause");
                      SocketThreadManager.getInstance().send(jsonObject.toString());
                    } catch (JSONException e) {
                      e.printStackTrace();
                    } catch (Exception e) {
                      e.printStackTrace();
                    }
                //  }
                  img_playanim.setBackgroundResource(R.drawable.anim_play);
                } else {
                 // if (mImHelper != null && mImHelper.isLogin()) {
                    try {
                      JSONObject jsonObject = new JSONObject();
                      jsonObject.put("code", 202);
                      jsonObject.put("act", "ctlvideo");
                      jsonObject.put("data", "resume");
                      SocketThreadManager.getInstance().send(jsonObject.toString());
                    } catch (JSONException e) {
                      e.printStackTrace();
                    } catch (Exception e) {
                      e.printStackTrace();
                    }
                 // }

                  img_playanim.setBackgroundResource(R.drawable.anim_pause);
                }
              } else {
                playvideo(mMainPageResult.clause.get(0).clause_id, "radio",
                    videoNum, img_playanim);

                img_playanim.setBackgroundResource(R.drawable.anim_pause);

                for (int i = 0; i < imgList.size(); i++) {
                  if (i != videoNum) {
                    imgList.get(i).setBackgroundResource(R.drawable.anim_play);
                  }
                }
              }
            }
          }
        }
      });

      // if (i != pCount - 1) {
      // line = new View(mContext);
      // line.setBackgroundColor(0xffeeeeee);
      // custom_channel.addView(line, new LinearLayout.LayoutParams(
      // LayoutParams.MATCH_PARENT, 2));
      // }
    }
  }

  @Override
  public void setUserVisibleHint(boolean isVisibleToUser) {
    super.setUserVisibleHint(isVisibleToUser);
    if (getUserVisibleHint()) {

      LeConfig.isInternetAvailable = Tools.isNetworkAvailable(getActivity());

      if (SocketThreadManager.getInstance() != null) {
        SocketThreadManager.getInstance().removeDeviceStateListener(TabIndexFragment.this);
        SocketThreadManager.getInstance().setDeviceStateListener(
                TabIndexFragment.this);

        SocketThreadManager.getInstance().requestDeviceDetails();
      }

      LeMachine lm = LeXiaoXiaoBanApp.getInstance().getBaby();
      if (lm != null && tv_name != null) {
        if (Tools.isNotNullStr(lm.name)) {
          tv_name.setText(lm.name);
        }
      }

      isVisible = true;
      if (!isPrepared || Tools.isEmpty(selectQueryDate)) {
        return;
      } else {
        loadHabitsPlan(selectQueryDate);
      }

      handler.postDelayed(new Runnable() {
        @Override
        public void run() {
          try {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("code", 202);
            jsonObject.put("act", "videostatu");
            SocketThreadManager.getInstance().send(jsonObject.toString());
          } catch (JSONException e) {
            e.printStackTrace();
          } catch (Exception e) {
            e.printStackTrace();
          }
        }
      }, 500);

    } else {
      isVisible = false;
      releaseMp3Player();
    }
  }

  /**
   * 1:首页->成长概况 无入口 2:首页->成长概况 测试入口
   */
  private int TEST_MODE;

  @Override
  public void onClick(View v) {
    Intent intent = new Intent();
    switch (v.getId()) {
    case R.id.tv_recustom:
      intent.setClass(getActivity(), MyPainPointSelectActivity.class);
      intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
      startActivity(intent);
      break;
    // case R.id.view_growinfo:
    case R.id.headicon:
//      if (LeConfig.isLogin) {
        startActivity(new Intent(getActivity(),
            PersonalInformationActivity2.class));
//      } else {
//        Intent intent0 = new Intent(getActivity(), LoginActivity.class);
//        intent0.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
//        startActivity(intent0);
//      }
      break;
    case R.id.view_nameage:
    case R.id.view_score:
      if (btn_customclass.getVisibility() == View.VISIBLE) {
        TEST_MODE = 2;
        intent.setClass(getActivity(), AbilityTestExplainActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
        startActivity(intent);
      } else {
        TEST_MODE = 1;
        intent.putExtra("TEST_MODE", TEST_MODE);
        intent.putExtra("frommainpage", true);
        intent.setClass(getActivity(), HistoryTestResultActivity.class);
        startActivity(intent);
      }

      break;
    case R.id.btn_customclass:
      TEST_MODE = 2;
      intent.setClass(getActivity(), AbilityTestExplainActivity.class);
      intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
      startActivity(intent);
      break;
    case R.id.btn_beginclass:
      break;
//    case R.id.view_more:
//      startActivity(new Intent(getActivity(), PrivatechannelActivity.class));
//      break;

    case R.id.device_stateview:
//      if (LeConfig.isLogin) {
        startActivity(new Intent(getActivity(), DevicePropertyActivity.class));
//      } else {
//        Intent intent0 = new Intent(getActivity(), LoginActivity.class);
//        intent0.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
//        startActivity(intent0);
//      }
      break;

    case R.id.rela_btnPreMonth:
      if (myCalenderFragment != null) {
        myCalenderFragment.pagerLast();
      }
      break;
    case R.id.rela_btnNextMonth:
      if (myCalenderFragment != null) {
        myCalenderFragment.pagerNext();
      }
      break;
    }
  }

  @SuppressLint("SimpleDateFormat")
  @Override
  public void onResume() {
    super.onResume();
    MobclickAgent.onPageStart(TAG);

    mLeUser = LeXiaoXiaoBanApp.getInstance().getUser();
    if (mLeUser != null) {
      if (Tools.isNotNullStr(mLeUser.machine)) {
        tv_name.setText(mLeUser.machine.name);
      }
    }

    handler.removeMessages(1);
    handler.sendEmptyMessageDelayed(1, 5000);

    getPainpointList();

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    String strToday = sdf.format(Calendar.getInstance().getTime());

    if (Tools.isNotEmpty(selectQueryDate)) {
      loadDataByMonth(selectQueryDate);
      loadHabitsPlan(selectQueryDate);
    } else {
      loadDataByMonth(strToday);
      loadHabitsPlan(strToday);
    }

    // handler.postDelayed(scheduleTask, 60 * 1000);
  }

  @SuppressLint("SimpleDateFormat")
  private void checkBabyAge() {
    LeUser lu = LeXiaoXiaoBanApp.getInstance().getUser();
    if (lu != null) {
      if (Tools.isNotNullStr(lu.machine)) {
        tv_name.setText(lu.machine.name);
      }

      if (Tools.isNotEmpty(lu.machine)) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        try {
          Calendar bef = Calendar.getInstance();
          bef.setTime(sdf.parse(lu.machine.dob));

          int month = Calendar.getInstance().get(Calendar.MONTH)
              - bef.get(Calendar.MONTH);

          int year = Calendar.getInstance().get(Calendar.YEAR)
              - bef.get(Calendar.YEAR);

          int totalMonth = year * 12 + month;
          if (totalMonth == 0) {
            totalMonth = 1;
          }

          if (totalMonth < 12) {
            tv_age.setText(totalMonth + "个月");
            LeXiaoXiaoBanApp.getInstance().kidAge = (totalMonth + "个月");
          } else {
            int year1 = totalMonth / 12;
            int month1 = totalMonth % 12;

            if (month1 > 0) {
              tv_age.setText(year1 + "岁" + month1 + "个月");
              LeXiaoXiaoBanApp.getInstance().kidAge = (year1 + "岁" + month1 + "个月");
            } else {
              tv_age.setText(year1 + "岁");
              LeXiaoXiaoBanApp.getInstance().kidAge = (year1 + "岁");
            }
          }
        } catch (Exception e) {
          // TODO: handle exception
        }
      }
    }
  }

  private void playvideo(final int sid, final String status,
      final int clause_num, final ImageView img) {
    new CustomAsyncTask(getActivity(), new IAsyncTask() {
      @Override
      public void onRecieveData(Activity activity, ResponseResult result) {
        if (result.isSuccess()) {
          Toast.makeText(getActivity(), "已推送到设备播放", Toast.LENGTH_SHORT)
                  .show();
        } else {
          if (Tools.isNotNullStr(result.data)) {
            Toast.makeText(getActivity(), result.data, Toast.LENGTH_SHORT)
                .show();
          }

          img.setBackgroundResource(R.drawable.anim_play);
        }

        btn_beginclass.setBackgroundResource(R.drawable.begin_class_normal);
      }

      @SuppressWarnings("unused")
      @Override
      public ResponseResult doInbackground(Activity activity) {
        HashMap<String, Object> param_ = new HashMap<String, Object>();

        int uid = -1, volume = -1, minutes = -1;
        LeUser lu = LeXiaoXiaoBanApp.getInstance().getUser();

        if (lu == null) {
          lu = Tools.restoreLeUser();
        }

        param_.put(HttpUtils.TAG_SNO_I, lu.sno);
        param_.put(HttpUtils.TAG_KEY_I, HttpUtils.KEY);
        param_.put(HttpUtils.TAG_ACTION_I, "play");
        param_.put(HttpUtils.TAG_OPERATION_I, "clause");

        param_.put("clause_num", String.valueOf(clause_num + 1));
        if (sid != -1) {
          param_.put(HttpUtils.TAG_VIDEO_ID_I, String.valueOf(sid));
        }
        param_.put(HttpUtils.TAG_PLAY_MODE, String.valueOf(LeConfig.PlayMode));

        return HttpUtils.startRequest(HttpUtils.API_URL
            + HttpUtils.OPERATE_DEVICE_METHOD_GET, param_,
            HttpUtils.TAG_GET_REQUEST);

      }
    }).execute();
  }

  @Override
  public void onDestroy() {
    super.onDestroy();
    if (handler != null) {
      handler.removeCallbacksAndMessages(null);
      handler = null;
    }

    try {
      if (mContext != null && mReceiver != null) {
        mContext.unregisterReceiver(mReceiver);
        mReceiver = null;
      }
    } catch (Exception e) {
    }


    unBind();

    releaseMp3Player();
  }

  @Override
  public void onGridItemClik(int pos) {
    Toast.makeText(getActivity(), "内容分类" + pos, Toast.LENGTH_SHORT).show();
    mCategoryListAdapter.notifyDataSetChanged();
  }

  @Override
  public void onScrollStateChanged(AbsListView view, int scrollState) {
    // TODO
  }

  @Override
  public void onScroll(AbsListView view, int firstVisibleItem,
      int visibleItemCount, int totalItemCount) {
    // TODO
  }

  @Override
  public void onCompletion(MediaPlayer arg0) {
    // TODO
  }

  @Override
  public void onRefresh(RefreshableView view) {
    if (loading) {
      mRefreshableView.finishRefresh();
    } else {
      // loadCurrentWeekCalendar();
      firstLoad = true;
      loadDataByMonth(selectQueryDate);
    }
  }

  @Override
  public void onCheckClick() {
    // TODO
  }

  // 家长修改教师习惯
  @Override
  public void finishSetAlarm2() {
    loadHabitsPlan(selectQueryDate);
    // {"code":"app","act":"habit_start/habit_pause/habit_update","data":""}
    JSONObject jsonObject = new JSONObject();
    try {
      jsonObject.put("code", 202);
      jsonObject.put("act", "habit_update");
      jsonObject.put("data", mLeUser.id);

      SocketThreadManager.getInstance().send(jsonObject.toString());
      lastIMContent = jsonObject.toString();
    } catch (JSONException e) {
      e.printStackTrace();
    }
  }

  @Override
  public void finishSetAlarm() {
    loadHabitsPlan(selectQueryDate);
    // {"code":"app","act":"habit_start/habit_pause/habit_update","data":""}
    JSONObject jsonObject = new JSONObject();
    try {
      jsonObject.put("code", 202);
      jsonObject.put("act", "habit_update");
      jsonObject.put("data", mLeUser.id);

      SocketThreadManager.getInstance().send(jsonObject.toString());
      lastIMContent = jsonObject.toString();
    } catch (JSONException e) {
      e.printStackTrace();
    }
  }

  @Override
  public void onDataReceived(final String data) {

    getActivity().runOnUiThread(new Runnable() {
      @Override
      public void run() {
       // mHabitMusic = null;
        if (Tools.isNotEmpty(data)) {
          try {
            JSONObject jsonData = new JSONObject(data.toString());
            if (Tools.isNotEmpty(jsonData) && !jsonData.isNull("act")
                    && jsonData.getString("act").contains("habit")) {
              String realData = jsonData.getString("data");
              if (Tools.isNotEmpty(realData)) {
                isPlayingMusic = true;
                mHabitMusic = JsonSerializer.getInstance().deserialize(realData,
                        HabitMedia.class);
                if (mHabitMusic != null) {
                  if (arrayListHabitPlan != null && arrayListHabitPlan.size() > 0) {
                    for (int i = 0; i < arrayListHabitPlan.size(); i++) {
                      HabitPlan item = arrayListHabitPlan.get(i);

                      if (item.is_customized == 1) {
                        if (item != null && item.id == mHabitMusic.id) {
                          item.allowEditTime = false;
                          listview_habitplan.setSelection(i);
                          break;
                        }
                      } else {
                        if (item != null && item.id == mHabitMusic.id) {
                          item.allowEditTime = false;
                          listview_habitplan.setSelection(i);
                          break;
                        }
                      }


                    }
                  }

                  if (Tools.isNotEmpty(mHabitMusic.PlayState)
                          && mHabitMusic.PlayState.contains("stop")) {
                    isPlayingMusic = false;
                  }

                  if (mHabitPlanAdapter != null) {
                    mHabitPlanAdapter.updatePlayingInfo(mHabitMusic);
                  }
                }
              }
            } else if (Tools.isNotEmpty(jsonData) && !jsonData.isNull("code")
                    && jsonData.getString("code").contains("server")) {
              String loginStr = jsonData.getString("act");
              if (Tools.isNotEmpty(loginStr)) {
                if (loginStr.contains("Device_Login")) {
                  LeConfig.isDeviceConnect = true;
                } else if (loginStr.contains("Device_Logout")) {
                  LeConfig.isDeviceConnect = false;
                } else if (loginStr.contains("Device_APP_Connection_Switched")) {
                  // Jump to Login page
                  LeConfig.isDeviceConnect = true;
                  SocketThreadManager.getInstance().releaseInstance();

                  // Intent logoutIntent = new Intent(
                  // "com.jdy.haoduoai.activity.logout");
                  // getActivity().sendBroadcast(logoutIntent);
                  //
                  // LeConfig.isLogin = false;
                  // LeConfig.isDeviceActivated = false;
                  // LeConfig.isDeviceBinded = false;
                  // LeConfig.isInfoFilled = false;
                  // LeConfig.isDeviceConnect = false;
                  //
                  // CustomOneBtnDialog.Builder cdb = new
                  // CustomOneBtnDialog.Builder(
                  // getActivity())
                  // .setTitle("下线通知")
                  // .setMessage("您有其他亲友正在连接控制小小班设备，请休息片刻。")
                  // .setPositiveButton("确定",
                  // new DialogInterface.OnClickListener() {
                  //
                  // @Override
                  // public void onClick(DialogInterface dialog, int which) {
                  // dialog.dismiss();
                  // }
                  // });
                  // final CustomOneBtnDialog cd = cdb.create();
                  // cd.getWindow().setType(
                  // WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
                  // cd.setOnDismissListener(new OnDismissListener() {
                  //
                  // @Override
                  // public void onDismiss(DialogInterface dialog) {
                  // Intent toActivityIntent = new Intent(getActivity(),
                  // LoginActivity.class);
                  // toActivityIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK
                  // | Intent.FLAG_ACTIVITY_CLEAR_TOP);
                  // startActivity(toActivityIntent);
                  // getActivity().finish();
                  // // dialog.dismiss();
                  // }
                  // });
                  // // cd.setCancelable(false);
                  // // cd.setCanceledOnTouchOutside(false);
                  // cd.show();
                }
              }
            } else if (Tools.isNotEmpty(jsonData) && !jsonData.isNull("code")
                    && jsonData.getString("code").contains("device")) {
              String loginStr = jsonData.getString("act");
              if (Tools.isNotEmpty(loginStr)) {
                if (loginStr.contains("Device_Login")) {
                  LeConfig.isDeviceConnect = true;
                } else if (loginStr.contains("Device_Logout")) {
                  LeConfig.isDeviceConnect = false;
                } else if (loginStr.contains("Device_APP_Connection_Switched")) {
                  // Jump to Login page
                  LeConfig.isDeviceConnect = true;
                  // Intent logoutIntent = new Intent(
                  // "com.jdy.haoduoai.activity.logout");
                  // getActivity().sendBroadcast(logoutIntent);
                  //
                  // LeConfig.isLogin = false;
                  // LeConfig.isDeviceActivated = false;
                  // LeConfig.isDeviceBinded = false;
                  // LeConfig.isInfoFilled = false;
                  // LeConfig.isDeviceConnect = false;
                  //
                  // CustomOneBtnDialog.Builder cdb = new
                  // CustomOneBtnDialog.Builder(
                  // getActivity())
                  // .setTitle("下线通知")
                  // .setMessage("您有其他亲友正在连接控制小小班设备，请休息片刻。")
                  // .setPositiveButton("确定",
                  // new DialogInterface.OnClickListener() {
                  //
                  // @Override
                  // public void onClick(DialogInterface dialog, int which) {
                  // dialog.dismiss();
                  // }
                  // });
                  // final CustomOneBtnDialog cd = cdb.create();
                  // cd.getWindow().setType(
                  // WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
                  // cd.setOnDismissListener(new OnDismissListener() {
                  //
                  // @Override
                  // public void onDismiss(DialogInterface dialog) {
                  // Intent toActivityIntent = new Intent(getActivity(),
                  // LoginActivity.class);
                  // toActivityIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK
                  // | Intent.FLAG_ACTIVITY_CLEAR_TOP);
                  // startActivity(toActivityIntent);
                  // getActivity().finish();
                  // // dialog.dismiss();
                  // }
                  // });
                  // // cd.setCancelable(false);
                  // // cd.setCanceledOnTouchOutside(false);
                  // cd.show();
                }
              }
            }
          } catch (JSONException e) {
            e.printStackTrace();
          }
        }
      }
    });
  }

  @Override
  public void onPause() {
    super.onPause();

    MobclickAgent.onPageEnd(TAG);
    handler.removeMessages(1);
  }

  @Override
  public void onDateSelected(String date) {
    loadDataByMonth(date);
    loadHabitsPlan(date);
    selectQueryDate = date;

    if (Tools.isNotEmpty(date)) {
      tvDate.setText(date.subSequence(0, 4) + "年" + date.substring(5, 7) + "月");
    }

  }

  @SuppressLint("SimpleDateFormat")
  @Override
  public void changeDate(String date, String viewType) {
    if (Tools.isEmpty(date)) {
      return;
    }

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

    String firstDayThisWeek = null, endDayThisWeek = null, firstDayThisMonth = null, endDayThisMonth = null;

    Date dateee;
    try {
      dateee = sdf.parse(date);
      Calendar cal = Calendar.getInstance();
      cal.setTime(dateee);
      cal.set(Calendar.DAY_OF_WEEK, 1);
      cal.getTime();
      firstDayThisWeek = sdf.format(cal.getTime()) + "";

      cal = Calendar.getInstance();
      cal.setTime(dateee);
      cal.set(Calendar.DAY_OF_MONTH, 1);
      cal.getTime();
      firstDayThisMonth = sdf.format(cal.getTime()) + "";

      cal = Calendar.getInstance();
      cal.setTime(dateee);
      cal.getTime();
      cal.set(Calendar.DAY_OF_WEEK, cal.getActualMaximum(Calendar.DAY_OF_WEEK));
      endDayThisWeek = sdf.format(cal.getTime()) + "";

      cal = Calendar.getInstance();
      cal.setTime(dateee);
      cal.set(Calendar.DAY_OF_MONTH,
          cal.getActualMaximum(Calendar.DAY_OF_MONTH));
      endDayThisMonth = sdf.format(cal.getTime()) + "";
    } catch (ParseException e) {

      e.printStackTrace();
    }

    String year = date.substring(0, 4);
    String month = date.substring(5, 7);

    tvDate.setText(year + "年" + month + "月");

    isPageChanged = true;
    mCustomDate = date;

    LeUser lu = LeXiaoXiaoBanApp.getInstance().getUser();
    if (lu == null) {
      lu = Tools.restoreLeUser();
    }

    if (Tools.isNotEmpty(lu) && mCustomDate != null) {
      LeMachine lm = lu.machine;
      String dateNow = mCustomDate.substring(0, mCustomDate.length() - 3);

      if (lm != null && lm.dob.contains(dateNow)) {
        if (myCalenderFragment != null) {
          myCalenderFragment.setMonthViewScrollble(false);
        }
      } else {
        if (myCalenderFragment != null) {
          myCalenderFragment.setMonthViewScrollble(true);
        }
      }
    } else {
      if (myCalenderFragment != null) {
        myCalenderFragment.setMonthViewScrollble(true);
      }
    }

    if (isPageChanged) {
      String dateString = date;

      if (!dateString.contains(mCurDay)) {
        dateString = dateString.substring(0, 7) + "-01";
      }

      String queryDateStr = mCustomDate;

      if (viewType.contains("week")) {
        if (myCalenderFragment.getSelectTime().compareTo(endDayThisWeek) <= 0
            && myCalenderFragment.getSelectTime().compareTo(firstDayThisWeek) >= 0) {
          queryDateStr = myCalenderFragment.getSelectTime();
        } else {
          queryDateStr = firstDayThisWeek;
        }

        loadDataByMonth(queryDateStr);
        loadHabitsPlan(queryDateStr);
        selectQueryDate = queryDateStr;
      } else {
        if (myCalenderFragment.getSelectTime().compareTo(endDayThisMonth) <= 0
            && myCalenderFragment.getSelectTime().compareTo(firstDayThisMonth) >= 0) {
          queryDateStr = myCalenderFragment.getSelectTime();
        } else {
          queryDateStr = firstDayThisMonth;
        }

        loadDataByMonth(queryDateStr);
        loadHabitsPlan(queryDateStr);
        selectQueryDate = queryDateStr;
      }
    }
  }

  @Override
  public void onRemoteLogin() {
    // TODO Auto-generated method stub

  }

  @Override
  public void onConnectionChanged(boolean connect) {
    // TODO Auto-generated method stub

  }

  @Override
  public void onPowerChanged(int power) {
    // TODO Auto-generated method stub

  }

  @Override
  public void onUpgrade(int updatingStatus) {
    // TODO Auto-generated method stub

  }

  @Override
  public void onCheckDeviceVersion(String version) {
    // TODO Auto-generated method stub

  }

  @Override
  public void onPlayNextFailed() {
    // TODO Auto-generated method stub

  }

  @Override
  public void onPlayPrevFailed() {
    // TODO Auto-generated method stub

  }

  @Override
  public void onPlayMedia(final PlayState playState, MediaType type,
                          final JSONObject data) {

    getActivity().runOnUiThread(new Runnable() {

      @Override
      public void run() {
        mPlayState = playState;

        String playType = "radio";
        if (data.has("type")) {
          playType = data.optString("type");
        }

        if (playState.equals(PlayState.Playing)) {

          if (data.has("VideoId")) {
            mVideoId = data.optInt("VideoId");
            if (!imgList.isEmpty()) {
              for (ImageView img : imgList) {
                int tag = (int) img.getTag();
                if (tag == mVideoId) {
                  img.setBackgroundResource(R.drawable.anim_pause);
                } else {
                  img.setBackgroundResource(R.drawable.anim_play);
                }
              }
            }
          }

          if (Tools.isNotEmpty(playType)
              && playType.equalsIgnoreCase("game")) {
            // 更新互动游戏
            if (mMyTaskAdapter != null) {
              mMyTaskAdapter.updateWidgetStatus(mVideoId, mPlayState);
            }
          } else {
            if (mMyTaskAdapter != null) {
              mMyTaskAdapter.updateWidgetStatus(-1, PlayState.None);
            }
          }
        } else if (playState.equals(PlayState.Pause)) {

          if (data.has("VideoId")) {
            mVideoId = data.optInt("VideoId");
          }
          if (!imgList.isEmpty()) {
            for (ImageView img : imgList) {
              img.setBackgroundResource(R.drawable.anim_play);
            }
          }

          if (Tools.isNotEmpty(playType)
              && playType.equalsIgnoreCase("game")) {
            // 更新互动游戏
            if (mMyTaskAdapter != null) {
              mMyTaskAdapter.updateWidgetStatus(mVideoId, mPlayState);
            }
          } else {
            if (mMyTaskAdapter != null) {
              mMyTaskAdapter.updateWidgetStatus(-1, PlayState.None);
            }
          }
        } else {
          mVideoId = -1;

          if (!imgList.isEmpty()) {
            for (ImageView img : imgList) {
              img.setBackgroundResource(R.drawable.anim_play);
            }
          }

          if (Tools.isNotEmpty(playType)
              && playType.equalsIgnoreCase("game")) {
            // 更新互动游戏
            if (mMyTaskAdapter != null) {
              mMyTaskAdapter.updateWidgetStatus(mVideoId, mPlayState);
            }
          }
        }

      }
    });

  }

  @Override
  public void onReceivedVoiceMessage(String streamUrl) {
    // TODO Auto-generated method stub

  }

  @Override
  public void onScroll(int l, int t, int oldl, int oldt) {
    mRefreshableView.setBackgroundColor(0xff2bacfc);
    // float newAlpha = (float) t / 500;
    //
    // int height = scroll_view.getHeight();
    // int scrollViewMeasuredHeight = scroll_view.getChildAt(0)
    // .getMeasuredHeight();
    // int dis = scrollViewMeasuredHeight - height;
    // if (dis > 0) {
    // newAlpha = (float) t / dis;
    // }
    //
    // if (newAlpha >= 0.8 && newAlpha <= 1.0) {
    // mRefreshableView.setBackgroundColor(0xfff1f1f1);
    // } else {
    // mRefreshableView.setBackgroundColor(0xff25a2f0);
    // }

    if (t > 200) {
      mRefreshableView.setBackgroundColor(0xfff1f1f1);
    } else {
      mRefreshableView.setBackgroundColor(0xff2bacfc);
    }

    Log.e("hfhhhhfhhffhfffff", "t===" + t + "   oldt ======" + oldt);

  }

  public void OnConfirmClick(int pos) {
if (arrayListTeacherClass != null && pos < arrayListTeacherClass.size()) {
  arrayListTeacherClass.get(pos).checked = 1;
  mTeacherClassApater.setData(arrayListTeacherClass);
    }
  }
}
